package com.zmyuan.demo.netty.websocket.socket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;

/**
 * Created by zdb on 2017/2/15.
 */
public class WebsocketServerHandler extends ChannelInboundHandlerAdapter {

    private WebSocketServerHandshaker handshaker;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 建立连接
        if(msg instanceof FullHttpRequest) {
            FullHttpRequest req = (FullHttpRequest)msg;
            if(req.decoderResult().isSuccess() && req.headers().get("Upgrade").equals("websocket")) {
                WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory("ws://localhost:8999/websocket", null, false);
                handshaker = factory.newHandshaker(req);
                if(handshaker == null) {
                    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                } else {
                    handshaker.handshake(ctx.channel(), req);
                }
            } else {
                // 输出bad响应
                DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
                if(response.status().code() != 200) {
                    ByteBuf buf = Unpooled.copiedBuffer("请求异常", CharsetUtil.UTF_8);
                    response.content().writeBytes(buf);
                    buf.release();
                }
                ctx.writeAndFlush(response);
            }
        } else if(msg instanceof WebSocketFrame) {
            if(msg instanceof CloseWebSocketFrame) {
                handshaker.close(ctx.channel(), (CloseWebSocketFrame)msg);
            } else if(msg instanceof TextWebSocketFrame) {
                String req = ((TextWebSocketFrame)msg).text();
                ctx.writeAndFlush(new TextWebSocketFrame(req + "服务端返回数据"));
            }
        }


    }


}
